<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :showBefore="true">
        <!-- 左侧显示总记录条数 -->
        <template #before>
          <span>总共{{ page.total }}条信息</span>
        </template>

        <!-- 右侧  excel导入 excel 导出 新增员工 -->
        <template #after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >Excel 导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >Excel 导出</el-button
          >
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPermission('POINT-USER-ADD')"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            sortable=""
            align="center"
            width="80"
            type="index"
          />
          <el-table-column
            label="姓名"
            sortable=""
            align="center"
            prop="username"
          />
          <el-table-column
            label="头像"
            sortable=""
            width="130"
            prop="staffPhoto"
            align="center"
          >
            <template #default="{ row }">
              <!-- <el-image
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                style="width: 100px; height: 100px; border-radius: 50%"
                :src="row.staffPhoto"
                :preview-src-list="srcList"
              ></el-image> -->
              <img
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width: 100px; height: 100px; border-radius: 50%"
                @click="showQrCode(row.staffPhoto)"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column
            label="工号"
            sortable=""
            prop="workNumber"
            align="center"
          />
          <el-table-column
            label="手机号"
            sortable=""
            prop="mobile"
            align="center"
          />
          <el-table-column
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
            prop="formOfEmployment"
            align="center"
          />
          <el-table-column
            label="部门"
            sortable=""
            prop="departmentName"
            align="center"
          />
          <el-table-column
            label="入职时间"
            sortable=""
            prop="timeOfEntry"
            align="center"
          >
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
            prop="enableState"
            align="center"
            ><template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" /> </template
          ></el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                :disabled="!checkPermission(pointDel)"
                size="small"
                @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee :showDialog="showDialog" :userId="userId" />
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
      @close="imgUrl = ''"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <assign-role
      :showRoleDialog.sync="showRoleDialog"
      :user-id="userId"
      ref="assignRole"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from "@/api/employees";
// 枚举数据
import Employees from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import { formatDate } from "@/filters";
import QrCode from "qrcode";
import AssignRole from "./components/assign-role.vue";
import store from "@/store";
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      // 表格数据
      list: [],
      // 分页数据
      page: {
        // 页码
        page: 1,
        // 显示条数
        size: 10,
        // 总条数
        total: 0,
      },
      // 加载提示
      loading: true,
      // 模态框状态
      showDialog: false,
      // 二维码模态框
      showCodeDialog: false,
      // 权限模态框
      showRoleDialog: false,
      // 用户id
      userId: null,
      // 删除操作标识
      pointDel: null,
    };
  },
  created() {
    this.getEmployeeList();
    this.filterPoint();
  },
  methods: {
    // 分页
    changePage(newPage) {
      this.page.page = newPage;
      this.getEmployeeList();
    },
    // 获取数据
    async getEmployeeList() {
      this.loading = true;
      const { total, rows } = await getEmployeeList(this.page);
      this.page.total = total;
      this.list = rows;
      this.srcList = rows.map((item) => item.staffPhoto);
      this.loading = false;
    },
    // 枚举聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 循环聘用形式,查找 id 和当前编号相同的数据
      const obj = Employees.hireType.find((item) => item.id === cellValue);
      // 判断有没有数据，有的话返回聘用形式，没有的话返回 未知
      return obj ? obj.value : "未知";
    },
    // 删除
    async delEmployee(id) {
      try {
        await this.$confirm("确认删除该员工吗？");
        // 点击确定后执行
        await delEmployee(id);
        this.$message.success("删除成功");
        // 重新获取数据
        this.getEmployeeList();
      } catch (error) {
        console.log(error);
      }
    },
    // 导出 Excel
    exportData() {
      // 表头对应关系
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };

      // 点击后导入这个模块
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 获取员工所有数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        // 要转换数据结构还要和表头的顺序对上
        const data = this.formatJson(headers, rows);
        // 复杂表头
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        // 合并表头
        const merges = ["A1:A2", "B1:F1", "G1:G2"];
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: data,
          filename: "员工入职表",
          autoWidth: true,
          multiHeader,
          merges,
        });
      });
    },
    // 将表头数据 [{}]和数据进行对应 [[]]
    formatJson(headers, rows) {
      // 遍历总数据
      return rows.map((item) => {
        // 遍历表头里面的键
        return Object.keys(headers).map((key) => {
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return formatDate(item[headers[key]]); // 返回格式化之前的时间
          } else if (headers[key] === "formOfEmployment") {
            // 枚举聘用形式
            const obj = Employees.hireType.find(
              (obj) => obj.id === item[headers[key]]
            );
            return obj ? obj.value : "未知";
          }
          // headers[key]  接口对应的属性
          // item[headers[key]] 根据 headers 里面的值，找到对应的数据
          // 返回出去
          return item[headers[key]];
        });
      });
    },
    // 显示二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true;
        // 因为页面渲染是异步的，打开的时候数据还没有更新
        // 有一个方法可以在上一次数据更新完毕 渲染完毕之后执行
        this.$nextTick(() => {
          // 此时就有了 ref
          QrCode.toCanvas(this.$refs.myCanvas, url);
        });
      } else {
        this.$message.warning("该用户还未上传头像");
      }
    },
    // 编辑角色
    async editRole(id) {
      this.userId = id;
      // 调用子组件的获取角色方法，根据当前用户 id 查找
      await this.$refs.assignRole.getRoleDetail(id);
      this.showRoleDialog = true;
    },
    // 处理权限标识
    filterPoint() {
      const { roles } = store.state.user.userInfo;
      console.log(roles.points);
      roles.points.some((item) => {
        if (item.includes("DEL") || item.includes("del")) {
          this.pointDel = item;
          return true;
        }
      });
      console.log(this.pointDel);
      // console.log(store.state.user.userInfo);
    },
  },
};
</script>

<style></style>
